package com.bookstore.back.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bookstore.back.common.Result;
import com.bookstore.back.entity.UserAddress;
import com.bookstore.back.service.CartService;
import com.bookstore.back.service.UserAddressService;
import com.bookstore.back.service.UserFavoriteService;
import com.bookstore.back.service.UserProfileService;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 普通用户个人资料控制器
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserProfileService userProfileService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private UserFavoriteService userFavoriteService;

    @Autowired
    private CartService cartService;

    @Autowired
    private UserContextUtil userContextUtil;

    /**
     * 获取用户个人资料
     */
    @GetMapping("/profile")
    public Result<Map<String, Object>> getUserProfile() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            Map<String, Object> profile = userProfileService.getUserProfile();
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取用户个人资料失败：{}", e.getMessage());
            return Result.error("获取个人资料失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户个人资料
     */
    @PutMapping("/profile")
    public Result<String> updateUserProfile(@RequestBody Map<String, Object> profileData) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userProfileService.updateUserProfile(profileData);
            return success ? Result.success("个人资料更新成功") : Result.error("个人资料更新失败");
        } catch (Exception e) {
            log.error("更新用户个人资料失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改用户密码
     */
    @PutMapping("/password")
    public Result<String> changeUserPassword(@RequestBody Map<String, String> passwordData) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            String currentPassword = passwordData.get("currentPassword");
            String newPassword = passwordData.get("newPassword");

            if (currentPassword == null || currentPassword.trim().isEmpty()) {
                return Result.error("当前密码不能为空");
            }
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return Result.error("新密码不能为空");
            }
            if (newPassword.length() < 6) {
                return Result.error("新密码长度不能少于6位");
            }

            boolean success = userProfileService.changeUserPassword(currentPassword, newPassword);
            return success ? Result.success("密码修改成功") : Result.error("密码修改失败，请检查当前密码是否正确");
        } catch (Exception e) {
            log.error("修改用户密码失败：{}", e.getMessage());
            return Result.error("修改密码失败：" + e.getMessage());
        }
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/profile/avatar")
    public Result<Map<String, Object>> uploadUserAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            // 验证文件
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }

            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }

            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!isValidImageExtension(fileExtension)) {
                return Result.error("只支持 JPG、JPEG、PNG、GIF 格式的图片");
            }

            // 验证文件大小（2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.error("文件大小不能超过 2MB");
            }

            // 创建上传目录
            String uploadDir = "uploads/avatar/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(newFileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 构建返回的文件URL
            String fileUrl = "/" + uploadDir + "/" + newFileName;

            // 更新用户头像
            boolean updateSuccess = userProfileService.updateUserAvatar(fileUrl);
            if (!updateSuccess) {
                return Result.error("更新头像失败");
            }

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("originalName", originalFilename);
            result.put("size", file.getSize());
            result.put("message", "头像上传成功");

            log.info("用户头像上传成功：{}", fileUrl);
            return Result.success("头像上传成功", result);

        } catch (IOException e) {
            log.error("上传用户头像失败：{}", e.getMessage());
            return Result.error("上传头像失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("上传用户头像异常：{}", e.getMessage());
            return Result.error("上传头像失败");
        }
    }

    // ==================== 地址管理相关 ====================

    /**
     * 获取用户地址列表
     */
    @GetMapping("/addresses")
    public Result<List<UserAddress>> getUserAddressList() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            List<UserAddress> addresses = userAddressService.getUserAddressList();
            return Result.success(addresses);
        } catch (Exception e) {
            log.error("获取用户地址列表失败：{}", e.getMessage());
            return Result.error("获取地址列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取地址详情
     */
    @GetMapping("/addresses/{addressId}")
    public Result<UserAddress> getAddressById(@PathVariable Integer addressId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            UserAddress address = userAddressService.getAddressById(addressId);
            return Result.success(address);
        } catch (Exception e) {
            log.error("获取地址详情失败：{}", e.getMessage());
            return Result.error("获取地址详情失败：" + e.getMessage());
        }
    }

    /**
     * 添加用户地址
     */
    @PostMapping("/addresses")
    public Result<String> addUserAddress(@RequestBody Map<String, Object> addressData) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userAddressService.addUserAddress(addressData);
            return success ? Result.success("地址添加成功") : Result.error("地址添加失败");
        } catch (Exception e) {
            log.error("添加用户地址失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户地址
     */
    @PutMapping("/addresses/{addressId}")
    public Result<String> updateUserAddress(@PathVariable Integer addressId, @RequestBody Map<String, Object> addressData) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userAddressService.updateUserAddress(addressId, addressData);
            return success ? Result.success("地址更新成功") : Result.error("地址更新失败");
        } catch (Exception e) {
            log.error("更新用户地址失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除用户地址
     */
    @DeleteMapping("/addresses/{addressId}")
    public Result<String> deleteUserAddress(@PathVariable Integer addressId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userAddressService.deleteUserAddress(addressId);
            return success ? Result.success("地址删除成功") : Result.error("地址删除失败");
        } catch (Exception e) {
            log.error("删除用户地址失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/addresses/{addressId}/default")
    public Result<String> setDefaultAddress(@PathVariable Integer addressId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userAddressService.setDefaultAddress(addressId);
            return success ? Result.success("默认地址设置成功") : Result.error("默认地址设置失败");
        } catch (Exception e) {
            log.error("设置默认地址失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取默认地址
     */
    @GetMapping("/addresses/default")
    public Result<UserAddress> getDefaultAddress() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            UserAddress address = userAddressService.getDefaultAddress();
            return Result.success(address);
        } catch (Exception e) {
            log.error("获取默认地址失败：{}", e.getMessage());
            return Result.error("获取默认地址失败：" + e.getMessage());
        }
    }

    // ==================== 收藏管理相关 ====================

    /**
     * 添加收藏
     */
    @PostMapping("/favorites/{bookId}")
    public Result<String> addFavorite(@PathVariable Integer bookId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userFavoriteService.addFavorite(bookId);
            return success ? Result.success("收藏成功") : Result.error("收藏失败");
        } catch (Exception e) {
            log.error("添加收藏失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/favorites/{bookId}")
    public Result<String> removeFavorite(@PathVariable Integer bookId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userFavoriteService.removeFavorite(bookId);
            return success ? Result.success("取消收藏成功") : Result.error("取消收藏失败");
        } catch (Exception e) {
            log.error("取消收藏失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 切换收藏状态
     */
    @PostMapping("/favorites/{bookId}/toggle")
    public Result<Map<String, Object>> toggleFavorite(@PathVariable Integer bookId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean isFavorite = userFavoriteService.toggleFavorite(bookId);
            Map<String, Object> result = new HashMap<>();
            result.put("isFavorite", isFavorite);
            result.put("message", isFavorite ? "收藏成功" : "取消收藏成功");
            return Result.success(result);
        } catch (Exception e) {
            log.error("切换收藏状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查收藏状态
     */
    @GetMapping("/favorites/{bookId}/status")
    public Result<Map<String, Object>> checkFavoriteStatus(@PathVariable Integer bookId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean isFavorite = userFavoriteService.isFavorite(bookId);
            Map<String, Object> result = new HashMap<>();
            result.put("isFavorite", isFavorite);
            return Result.success(result);
        } catch (Exception e) {
            log.error("检查收藏状态失败：{}", e.getMessage());
            return Result.error("检查收藏状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取收藏列表
     */
    @GetMapping("/favorites")
    public Result<Object> getUserFavorites(@RequestParam Map<String, Object> params) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            // 判断是否需要分页
            if (params.containsKey("current") && params.containsKey("size")) {
                IPage<Map<String, Object>> favoriteList = userFavoriteService.getUserFavoriteListPage(params);
                return Result.success(favoriteList);
            } else {
                List<Map<String, Object>> favoriteList = userFavoriteService.getUserFavoriteList();
                return Result.success(favoriteList);
            }
        } catch (Exception e) {
            log.error("获取收藏列表失败：{}", e.getMessage());
            return Result.error("获取收藏列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取收藏数量
     */
    @GetMapping("/favorites/count")
    public Result<Map<String, Object>> getFavoriteCount() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            int count = userFavoriteService.getUserFavoriteCount();
            Map<String, Object> result = new HashMap<>();
            result.put("count", count);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取收藏数量失败：{}", e.getMessage());
            return Result.error("获取收藏数量失败：" + e.getMessage());
        }
    }

    /**
     * 清空收藏
     */
    @DeleteMapping("/favorites")
    public Result<String> clearFavorites() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = userFavoriteService.clearUserFavorites();
            return success ? Result.success("清空收藏成功") : Result.error("清空收藏失败");
        } catch (Exception e) {
            log.error("清空收藏失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    // ==================== 购物车管理相关 ====================

    /**
     * 获取用户购物车列表
     */
    @GetMapping("/cart")
    public Result<List<Map<String, Object>>> getUserCart() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            List<Map<String, Object>> cartList = cartService.getUserCartList();
            return Result.success(cartList);
        } catch (Exception e) {
            log.error("获取用户购物车失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/cart")
    public Result<String> addToCart(@RequestBody Map<String, Object> cartData) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            Integer bookId = (Integer) cartData.get("bookId");
            Integer quantity = (Integer) cartData.getOrDefault("quantity", 1);

            if (bookId == null) {
                return Result.error("图书ID不能为空");
            }

            boolean success = cartService.addToCart(bookId, quantity);
            return success ? Result.success("添加到购物车成功") : Result.error("添加到购物车失败");
        } catch (Exception e) {
            log.error("添加商品到购物车失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/cart/{bookId}")
    public Result<String> updateCartQuantity(@PathVariable Integer bookId, @RequestBody Map<String, Object> data) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            Integer quantity = (Integer) data.get("quantity");
            if (quantity == null) {
                return Result.error("数量不能为空");
            }

            boolean success = cartService.updateCartQuantity(bookId, quantity);
            return success ? Result.success("更新数量成功") : Result.error("更新数量失败");
        } catch (Exception e) {
            log.error("更新购物车商品数量失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 从购物车删除商品
     */
    @DeleteMapping("/cart/{bookId}")
    public Result<String> removeFromCart(@PathVariable Integer bookId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = cartService.removeFromCart(bookId);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            log.error("从购物车删除商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/cart")
    public Result<String> clearCart() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            boolean success = cartService.clearCart();
            return success ? Result.success("清空购物车成功") : Result.error("清空购物车失败");
        } catch (Exception e) {
            log.error("清空购物车失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取购物车商品数量
     */
    @GetMapping("/cart/count")
    public Result<Integer> getCartCount() {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.success(0); // 未登录用户返回0
            }

            Integer count = cartService.getCartCount();
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取购物车商品数量失败：{}", e.getMessage());
            return Result.success(0);
        }
    }

    /**
     * 检查商品是否在购物车中
     */
    @GetMapping("/cart/{bookId}/status")
    public Result<Map<String, Object>> checkCartStatus(@PathVariable Integer bookId) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                Map<String, Object> result = new HashMap<>();
                result.put("inCart", false);
                return Result.success(result);
            }

            boolean inCart = cartService.isInCart(bookId);
            Map<String, Object> result = new HashMap<>();
            result.put("inCart", inCart);
            return Result.success(result);
        } catch (Exception e) {
            log.error("检查商品购物车状态失败：{}", e.getMessage());
            Map<String, Object> result = new HashMap<>();
            result.put("inCart", false);
            return Result.success(result);
        }
    }

    /**
     * 同步本地购物车数据（用于登录时）
     */
    @PostMapping("/cart/sync")
    public Result<String> syncCartFromLocal(@RequestBody Map<String, Object> data) {
        try {
            // 验证用户权限
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以访问");
            }

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> cartItems = (List<Map<String, Object>>) data.get("cartItems");

            if (cartItems == null || cartItems.isEmpty()) {
                return Result.success("无需同步");
            }

            boolean success = cartService.syncCartFromLocal(cartItems);
            return success ? Result.success("同步成功") : Result.error("同步失败");
        } catch (Exception e) {
            log.error("同步本地购物车数据失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查图片文件扩展名是否有效
     */
    private boolean isValidImageExtension(String extension) {
        return extension.equals(".jpg") || extension.equals(".jpeg") ||
               extension.equals(".png") || extension.equals(".gif");
    }
}
